package org.microdream.easy.deploy.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ice.server.comm.BaseServiceImpl;
import ice.server.comm.CommRepository;
import ice.server.comm.ParamBulider;
import org.microdream.easy.deploy.dao.DDictionaryRepository;
import org.microdream.easy.deploy.po.DDictionary;
import org.microdream.easy.deploy.utils.ListUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DDictionaryService extends BaseServiceImpl<DDictionary, Integer>{

    @Resource
    private DDictionaryRepository dDictionaryRepository;

    @Override
    public CommRepository<DDictionary, Integer> getRepository() {

        return dDictionaryRepository;
    }

    @Override
    public Integer getIdenty(DDictionary t) {
        return t.getId();
    }

    public JSONArray searchByType(String type) {
        List<DDictionary> dDictionaries = this.find(ParamBulider.build().addEqual("dicType",type).get());
        JSONArray jsonArray = new JSONArray();
        dDictionaries.forEach(dDictionary -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("value",dDictionary.getDicName());
            jsonObject.put("key",dDictionary.getDicValue());
            jsonArray.add(jsonObject);
        });
        return jsonArray;
    }

    public Map<String,String> initSingleMap(){
        Map<String,String> map = new HashMap<>();
        List<DDictionary> dDictionaries = this.findAll();
        dDictionaries.forEach(dDictionary -> {
            map.put(dDictionary.getDicType()+dDictionary.getDicValue(),dDictionary.getDicName());
        });
        return map;
    }

    public Map<String,List<DDictionary>> initListMap(){
        Map<String,List<DDictionary>> map = new HashMap<>();
        List<DDictionary> dDictionaries = this.findAll();
        List<String> types = dDictionaries.stream().map(DDictionary::getDicType).collect(Collectors.toList());
        types = ListUtil.removeDuplicate(types);
        types.forEach(s -> {
            map.put(s,dDictionaries.stream().filter(dDictionary -> dDictionary.getDicType().equals(s)).collect(Collectors.toList()));
        });
        return map;
    }
}
